﻿using System;
using System.Configuration;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using BLL.Enum;
using BLL.Installer;
using BLL.Interface.Base;
using BLL.Model.Base;
using Castle.MicroKernel;

namespace WayCloud.Plumbing
{
    public class WindsorControllerFactory : DefaultControllerFactory
    {
        private readonly IKernel _kernel;

        public WindsorControllerFactory(IKernel kernel)
        {
            _kernel = kernel;
        }

        public override void ReleaseController(IController controller)
        {
            _kernel.ReleaseComponent(controller);
        }

        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if (controllerType == null)
            {
                throw new HttpException(404, string.Format("The controller for path '{0}' could not be found.", requestContext.HttpContext.Request.Path));
            }

            SetUserInfo(requestContext);

            //SetLoginUserInfo(requestContext);
            return (IController)_kernel.Resolve(controllerType);
        }

        /// <summary>
        /// 对用户信息进行填充
        /// </summary>
        /// <param name="requestContext"></param>
        private static void SetUserInfo(RequestContext requestContext)
        {
            var userId = requestContext.HttpContext.Session[SessionParameterEnum.CurrentUserId] == null
                             ? string.Empty
                             : requestContext.HttpContext.Session[SessionParameterEnum.CurrentUserId].ToString();
            if (string.IsNullOrWhiteSpace(userId)) return;
            var loginHelperManager = ContainerHelper.Instance.Container.Resolve<ILoginHelper>();
            var user = loginHelperManager.FindLoginUserInfo(userId);
            if (user != null)
            {
                requestContext.HttpContext.User = new UserPrincipal(user);
            }
        }

        /// <summary>
        /// 针对用户的每次请求，对信息做出修改
        /// </summary>
        private static void SetLoginUserInfo(RequestContext requestContext)
        {
            var userId = requestContext.HttpContext.Session[SessionParameterEnum.CurrentUserId];
            var loginUserManager = ContainerHelper.Instance.Container.Resolve<ILoginHelper>();
            if (userId == null ||
                string.IsNullOrWhiteSpace(userId.ToString()) ||
                !loginUserManager.CheckUserIsLogin(userId.ToString()))
            {
                return;
            }

            var userInfo = loginUserManager.FindLoginUserInfo(userId.ToString());
            var timeout = Convert.ToDouble(ConfigurationManager.AppSettings["LoginTimeOut"]);
            var dateDiff = (DateTime.Now - userInfo.LastAccessTime).TotalMinutes;
            if (!timeout.Equals(0) && dateDiff > timeout)
            {
                requestContext.HttpContext.Session[SessionParameterEnum.CurrentUserId] = null;
            }
            else
            {
                userInfo.LastAccessTime = DateTime.Now;
            }
        }

    }
}